#!/bin/bash

function help {
    echo "Tool to create group of macros from a list values. The input file shall "
    echo ""
    echo "Usage:"
    echo "    $0  <input file>  <output file>"
}

if [ "$1" == "" ]; then
    help
    exit -1
fi

if [ "$2" == "" ]; then
    help
    exit -1
fi


trim() {
    local var=$1
    var="${var#"${var%%[![:space:]]*}"}"   # remove leading whitespace characters
    var="${var%"${var##*[![:space:]]}"}"   # remove trailing whitespace characters
    echo -n "$var"
}



echo "/* Generated file from file $1, do not change! */"  > $2
echo ""  >> $2
finame=$1
inputfilename=${finame##*/}
echo "#ifndef __${inputfilename}__"  >> $2
echo "#define __${inputfilename}__"  >> $2
echo ""  >> $2


tagarray=""
opisarray=""

firstline=1
elemcnt=0
while read line
do
    if [ $firstline == 1 ]; then
        IFS=' '
        prefixsuffix=($line)
        firstline=0
    else
        IFS=','
        cnt=0
        linearr=($line)
        if [ ${#linearr[@]} -gt 1 ]; then
            for word in $line
            do
               #echo $cnt $word
               trimmedeord=`trim $word`
               cnt=$(($cnt+1))
               if [ $cnt -eq 1 ]; then
                   echo '#define' ${prefixsuffix[0]}$word "($elemcnt)" >> $2
                   echo '#define' ${prefixsuffix[0]}$word${prefixsuffix[1]} '"'$word'"' >> $2
                   tagarray="$tagarray        "'"'$word'"'","'\\'"\n"
                   macrotag=$word
               fi
               if [ $cnt -gt 1 ]; then
                   echo '#define' ${prefixsuffix[0]}$macrotag${prefixsuffix[$cnt]} $trimmedeord >> $2
               fi
               if [ $cnt -eq 2 ]; then
                   opisarray="$opisarray      $trimmedeord,"'\\'"\n"
               fi
            done
            elemcnt=$(($elemcnt+1))
            echo ""  >> $2
        fi
    fi
done < $1


echo ""  >> $2
echo ""  >> $2
echo -e "#define ${prefixsuffix[0]}${prefixsuffix[1]}ARRAY "'\\'"\n$tagarray     NULL"  >> $2
echo ""  >> $2
echo -e "#define ${prefixsuffix[0]}${prefixsuffix[2]}ARRAY "'\\'"\n$opisarray     NULL"  >> $2
echo ""  >> $2
echo -e "#define ${prefixsuffix[0]}COUNT  ($elemcnt)"  >> $2
echo ""  >> $2
echo "#endif //__${inputfilename}__"  >> $2



exit 0